<template>
  <div class="popup-bg"></div>

  <header class="header-section">
    <div class="container">
      <div class="row align-items-center">
        <!-- 假设你有一个网站Logo图片，这里用一个div代替实际图片路径 -->
        <div class="col-auto logo">
          <img src="@/assets/images/logo.png" alt="Your Website Logo" class="logo-img">
        </div>
        <div class="col title">
          <h1 class="heading">聚职智能求职分析平台</h1>
        </div>
      </div>
    </div>
  </header>

  <div class="popup-login-signup">
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center">
        </div>
        <!-- Modal -->
          <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
              <nav class="tab-bar-top">
                <div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
<!--                  <a class="nav-item nav-link active" id="nav-login-tab" data-toggle="tab" href="#nav-login" role="tab" aria-controls="nav-login" aria-selected="true">登录</a>-->
                  <a class="nav-item nav-link" id="nav-signup-tab" data-toggle="tab" href="#nav-signup" role="tab" aria-controls="nav-signup" aria-selected="false">忘记密码</a>
                </div>
              </nav>
              <div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
                <div class="tab-pane fade show active" id="nav-login" role="tabpanel" aria-labelledby="nav-login-tab">
                  <el-form :model="formModel" :rules="rules" class="form-login-signup">
                    <el-form-item prop="username" class="form-label-group">
                      <label for="inputUserame">用户名</label>
                      <el-input v-model="formModel.username"
                                :prefix-icon="User"
                                placeholder="请输入用户名"
                                size="large"
                                autocomplete="off">
                      </el-input>
                    </el-form-item>

                    <el-form-item prop="phone" class="form-label-group">
                      <label for="inputEmail-1">手机号</label>
                      <el-input v-model="formModel.phone"
                                :prefix-icon="Phone"
                                placeholder="请输入电话号码"
                                size="large"
                                autocomplete="off">
                      </el-input>
                    </el-form-item>

                    <label for="code" class="code-label">验证码</label>
                    <el-form-item prop="code" class="form-label-group custom-code-layout">

                      <div class="flex-container">
                        <el-input
                            v-model="formModel.code"
                            :prefix-icon="Lock"
                            placeholder="请输入验证码"
                            size="large"
                            autocomplete="off">
                        </el-input>
                        <el-button
                            :disabled="isCountingDown || !formModel.phone"
                            @click="sendVerificationCode"
                            type="primary"
                            style="margin-top: 0; margin-left: 20px"> <!-- 添加上边距以与输入框拉开距离 -->
                          {{ isCountingDown ? `${countdown}s后重新发送` : '发送验证码' }}
                        </el-button>
                      </div>
                    </el-form-item>


                    <el-form-item prop="password" class="form-label-group">
                      <label for="inputPassword-1">密码</label>
                      <el-input v-model="formModel.password"
                                type="password"
                                :prefix-icon="Lock"
                                placeholder="请输入密码"
                                size="large"
                                autocomplete="off">
                      </el-input>
                    </el-form-item>

                    <el-button @click="handlePasswordReset" class="btn btn-lg btn-primary btn-block btn-color-hover text-uppercase uniform-button login-button">修改密码</el-button>
                  </el-form>
                </div>
              </div>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted, nextTick } from 'vue'
import { User, Lock, Phone } from '@element-plus/icons-vue'
import {userForgetPasswordService, userUpdatePasswordService} from "@/api/user.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const formModel = ref({
  username: '',
  password: '',
  phone: '',
  code: ''
})


const router = useRouter();

//自定义校验电话号码
function validatePhone(rule, value, callback) {
  // 这里是一个简单的正则表达式，用于匹配中国大陆的手机号码（11位数字，以1开头）
  // 注意：这只是一个简单的示例，实际中可能需要更复杂的验证
  const regex = /^1[3-9]\d{9}$/;
  if (value === '') {
    callback(new Error('请输入电话号码'));
  } else if (!regex.test(value)) {
    callback(new Error('请输入有效的11位手机号码'));
  } else {
    callback();
  }
}

//表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '请输入5~16位非空字符', trigger: 'blur' }
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '请输入5~16位非空字符', trigger: 'blur' }
  ],
  code:[
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入4位数字', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ]
}

const isCountingDown = ref(false); // 控制倒计时按钮状态
const countdown = ref(60); // 倒计时秒数
const code = ref(''); // 验证码

// 发送验证码的方法
const sendVerificationCode = async () => {
  if (!formModel.value.phone) {
    alert('请输入电话号码');
    return;
  }

  //使用后端进行发送验证码
  let result = await userForgetPasswordService(formModel.value.phone)
  code.value = result.data;
  ElMessage.success(result.message ? result.message : "验证码发送成功")
  // 发送成功后开始倒计时
  isCountingDown.value = true;
  startCountdown();

};

// 倒计时函数
const startCountdown = () => {
  let timer = null;
  return new Promise((resolve) => {
    timer = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0) {
        clearInterval(timer);
        isCountingDown.value = false;
        countdown.value = 60;
        resolve();
      }
    }, 1000);
  });
};

async function handlePasswordReset() {
  if (!isCountingDown.value) {
    await sendVerificationCode();
  }
  //使用后端进行修改密码
  let result = await userUpdatePasswordService(code.value, formModel.value.code, formModel.value.username,
      formModel.value.phone, formModel.value.password)
  ElMessage.success(result.message ? result.message : "密码修改成功")
  router.push('/login')
}
</script>

<style scoped>
@import '@/assets/css/reset.css';
@import '@/assets/css/style.css';
@import '@/assets/css/responsive.css';
@import '@/assets/css/bootstrap.min.css';
@import '@fortawesome/fontawesome-free/css/all.min.css';
@import '@/assets/css/login-reset.css';
.custom-code-layout {
  display: flex;
  flex-direction: column; /* 改变布局方向为列 */
}

.code-label {
  margin-bottom: 5px; /* 为验证码标签添加下边距 */
}

.flex-container {
  display: flex;
  align-items: center; /* 保持按钮与输入框垂直居中 */
}
</style>